1
Easy2Siksha
GNDU Question Paper-2022
B.A 2
nd
Semester
COMPUTER SCIENCE
(Programming Using C)
Time Allowed: Two Hours Maximum Marks: 75
Note: There are Eight questions of equal marks. Candidates are required to attempt any
Four questions
SECTION-A
1. (a) How do you define decision tables ? How are these different from flowchats ?
Illustrate the use of each through suitable examples.
(b) Find out the values of X, Y and Z in the following:
(F8F.C)
16
= (X)
8
=(Y)
10
= (Z)
2
2. Explain the following:
(a) ASCII Character Code
(b) Algorithm and its characteristics.
SECTION-B
3. (a) What is meant by hierarachy of operators ? Provide a brief outline of all operators
supported by C language along with their hierarchy within expressions and suitable
examples.
(b) Why C language is named so? Discuss its origin and provide the general structure of
C language program detailing our every construct in it.
2
Easy2Siksha
4. Differentiate between the following:
(a) printf() and scanf()
(b) Formated and Unformatted Console I/O functions.
SECTION-C
5. (a) What is an array? What are different types of array ? How do you create and use
these arrays? Explain.
(b) How do you define a String? What are String functions? How do you create array of
strings? Explain.
6. Differentiate between the following:
(a) for and do-while loops
(b) switch and if-else-if statements.
SECTION-D
7. Explain the following:
(a) Union and Structure
(b) Scope and lifetime of a variable
I Recursion.
8. Differentiate between the following:
(a) Call-by-value and call-by-reference
(b) Automatic, External and Static variables
I User Defined and Library Functions.
3
Easy2Siksha
GNDU Answer Paper-2022
B.A 2
nd
Semester
COMPUTER SCIENCE
(Programming Using C)
Time Allowed: Two Hours Maximum Marks: 75
Note: There are Eight questions of equal marks. Candidates are required to attempt any
Four questions
SECTION-A
1. (a) How do you define decision tables ? How are these different from flowchats ?
Illustrate the use of each through suitable examples.
(b) Find out the values of X, Y and Z in the following:
(F8F.C)
16
= (X)
8
=(Y)
10
= (Z)
2
Ans: Understanding Decision Tables and How They Differ from Flowcharts
When writing computer programs, it is essential to represent logic in a clear and organized
way. Two common tools for doing this are decision tables and flowcharts. While both serve
the purpose of illustrating processes or decisions, they do so in different ways and are
suited for different scenarios. Let us explore these tools in detail.
What Are Decision Tables?
A decision table is a structured way of representing a set of rules or conditions and their
corresponding actions. It organizes information in a tabular form, making it easier to
visualize and understand complex decision-making scenarios. Decision tables are especially
useful when dealing with multiple conditions and actions, as they provide a systematic way
to consider all possible combinations of conditions.
Structure of a Decision Table
A decision table typically consists of four parts:
1. Conditions: These are the criteria or rules that need to be evaluated.
4
Easy2Siksha
2. Condition Alternatives: These represent the possible values (e.g., "Yes" or "No") for
each condition.
3. Actions: These are the steps or decisions to be taken based on the evaluated
conditions.
4. Action Entries: These specify which actions to take for each combination of
condition alternatives.
Here is a simple decision table example:
Conditions
Alternative 1
Alternative 2
Alternative 3
Is it raining?
Yes
No
No
Have an umbrella?
Yes
Yes
No
Action
Go outside
Go outside
Stay inside
Example Explanation:
1. If it is raining and you have an umbrella, the decision is to go outside.
2. If it is not raining, you can go outside regardless of having an umbrella.
3. If it is raining and you do not have an umbrella, the decision is to stay inside.
Advantages of Decision Tables
Clarity: Clearly displays all possible scenarios.
Simplifies Complex Logic: Helps break down multiple conditions and their
corresponding actions.
Easy to Modify: Changes in rules can be reflected by updating the table.
What Are Flowcharts?
A flowchart is a visual representation of a process or system using symbols, shapes, and
arrows. It shows the sequence of steps in a process, helping to understand how decisions
and actions flow from one step to another. Flowcharts are commonly used to illustrate
algorithms, workflows, or system operations.
Structure of a Flowchart
Flowcharts use specific symbols to represent different steps:
1. Oval: Represents the start or end of a process.
2. Rectangle: Represents a process or task.
5
Easy2Siksha
3. Diamond: Represents a decision point.
4. Arrow: Shows the flow of control from one step to another.
Example Flowchart
Let us create a flowchart for the same decision-making process as the decision table
above:
1. Start.
2. Is it raining? (Decision point)
o Yes: Move to the next step.
o No: Go outside.
3. Do you have an umbrella? (Decision point)
o Yes: Go outside.
o No: Stay inside.
4. End.
The flowchart will look like this:
(Start) --> [Is it raining?] --> Yes --> [Have umbrella?] --> Yes --> (Go outside)
| |
No -----------------------------> (Stay inside)
No --> (Go outside)
Advantages of Flowcharts
Visual Representation: Easy to follow and understand the process flow.
Step-by-Step Illustration: Clearly shows the sequence of actions and decisions.
Debugging and Communication: Helps in identifying errors and explaining processes
to others.
Differences Between Decision Tables and Flowcharts
Feature
Decision Tables
Flowcharts
Format
Tabular format
Visual/diagrammatic format
Best For
Handling complex decision-
making
Illustrating the flow of processes
6
Easy2Siksha
Focus
Rules, conditions, and actions
Sequence of steps and decisions
Clarity in
Complexity
Better for multiple conditions
Can become cluttered with
complexity
Modification
Easier to update
Changes may require redrawing
When to Use Each Tool
Use a decision table when you need to deal with multiple conditions and want a
clear, comprehensive way to ensure all possibilities are covered.
Use a flowchart when you need to visualize the steps in a process or show how
decisions lead to actions.
Real-Life Analogy
Think of a decision table as a checklist for packing your bags. You consider conditions like
weather, duration, and type of trip, and then decide what to pack. On the other hand, a
flowchart is like a map that shows the route to your destination, including turns and stops
along the way.
Conclusion
Both decision tables and flowcharts are invaluable tools in programming and system design.
Decision tables excel at organizing complex logic with multiple conditions, while flowcharts
are better suited for visually representing the flow of processes. By understanding the
strengths and use cases of each, programmers can choose the right tool for the task at
hand, ensuring clarity, efficiency, and error-free implementation.
(b) Find out the values of X, Y and Z in the following:
(F8F.C)
16
= (X)
8
=(Y)
10
= (Z)
2
Ans: Understanding the Conversion of (F8F.C)₁₆ to Different Number Systems
In this explanation, we'll break down the process of converting the hexadecimal number
(F8F.C)₁₆ into its equivalents in octal (X), decimal (Y), and binary (Z) systems. We'll take it
step by step, ensuring clarity at each stage.
7
Easy2Siksha
1. What are Number Systems?
Before diving into the conversion process, let's briefly understand the four number systems
we'll be dealing with:
Hexadecimal (Base 16): Uses 16 symbols (0-9 and A-F). 'A' represents 10, 'B' is 11, up
to 'F,' which is 15.
Octal (Base 8): Uses 8 symbols (0-7).
Decimal (Base 10): The familiar system using symbols 0-9.
Binary (Base 2): Uses only two symbols (0 and 1).
2. Hexadecimal to Decimal Conversion
Let's first convert the hexadecimal number (F8F.C)₁₆ to decimal. This involves understanding
the place value for each digit in the hexadecimal system.
Step-by-Step Conversion:
1. Identify the place values:
o F8F.C₁₆ is structured as (F * 16²) + (8 * 16¹) + (F * 16⁰) + (C * 16⁻¹).
2. Convert each hexadecimal digit to decimal:
o F (hex) = 15 (decimal)
o 8 (hex) = 8 (decimal)
o F (hex) = 15 (decimal)
o C (hex) = 12 (decimal)
3. Calculate each term:
o (F * 16²) = 15 * 256 = 3840
o (8 * 16¹) = 8 * 16 = 128
o (F * 16⁰) = 15 * 1 = 15
o (C * 16⁻¹) = 12 * (1/16) = 0.75
4. Sum up the values:
o 3840 + 128 + 15 + 0.75 = 3983.75
Thus, (F8F.C)₁₆ = 3983.75₁₀.
3. Hexadecimal to Binary Conversion
Next, we convert (F8F.C)₁₆ directly to binary.
Step-by-Step Conversion:
8
Easy2Siksha
1. Convert each hexadecimal digit to its 4-bit binary equivalent:
o F (hex) = 1111 (binary)
o 8 (hex) = 1000 (binary)
o F (hex) = 1111 (binary)
o C (hex) = 1100 (binary)
2. Combine the binary groups:
o F8F.C (hex) = 1111 1000 1111.1100 (binary)
Thus, (F8F.C)₁₆ = 111110001111.1100₂.
4. Binary to Octal Conversion
Now, let's convert the binary number obtained into octal.
Step-by-Step Conversion:
1. Group binary digits in sets of three, starting from the decimal point:
o 1111 1000 1111.1100 becomes 1 111 100 011 111.110 000 (adding leading
zeros where necessary).
2. Convert each group to octal:
o 001 (binary) = 1 (octal)
o 111 (binary) = 7 (octal)
o 100 (binary) = 4 (octal)
o 011 (binary) = 3 (octal)
o 111 (binary) = 7 (octal)
o 110 (binary) = 6 (octal)
o 000 (binary) = 0 (octal)
3. Combine the octal digits:
o 1 747.60 (octal)
Thus, (F8F.C)₁₆ = 1747.6₈.
5. Recap and Summary
Hexadecimal (F8F.C)₁₆ converts to Decimal 3983.75₁₀.
It converts to Binary 111110001111.1100₂.
It converts to Octal 1747.6₈.
9
Easy2Siksha
6. Practical Example and Analogies
To solidify our understanding, let’s use an analogy:
Imagine you have a recipe written in a different language (hexadecimal). To cook the dish,
you need to translate the recipe into your native language (decimal), a friend's language
(octal), and another friend's language (binary). Each conversion ensures everyone
understands and can follow the recipe correctly.
7. Additional Practice
Let’s try converting another hexadecimal number:
Convert (1A3.B)₁₆ to decimal, binary, and octal:
Decimal Conversion:
1A3.B₁₆ = (1 * 16²) + (A * 16¹) + (3 * 16⁰) + (B * 16⁻¹)
1 (hex) = 1 (decimal)
A (hex) = 10 (decimal)
3 (hex) = 3 (decimal)
B (hex) = 11 (decimal)
(1 * 256) + (10 * 16) + (3 * 1) + (11 * 0.0625) = 256 + 160 + 3 + 0.6875 = 419.6875
Binary Conversion:
1A3.B (hex) = 0001 1010 0011.1011 (binary)
Octal Conversion:
Binary 0001 1010 0011.1011 becomes 1 010 001 011.101 100 (grouped into threes).
1 211.54 (octal)
Conclusion
Understanding these conversions helps in fields like computer science and electronics,
where different number systems are frequently used. Mastery of these conversions
enhances problem-solving skills and ensures a deeper grasp of the underlying concepts.
10
Easy2Siksha
2. Explain the following:
(a) ASCII Character Code
(b) Algorithm and its characteristics.
Ans: (a) ASCII Character Code
What is ASCII?
ASCII stands for American Standard Code for Information Interchange. It is a system used by
computers to represent characters like letters, numbers, and symbols in the form of
numbers. Think of it as a translator that helps computers understand human-readable text.
For example:
When you type the letter A, the computer sees it as the number 65 in ASCII.
Similarly, the lowercase a is represented as 97, and the number 1 is represented as
49.
Why do we need ASCII?
Computers can only understand numbers, not letters or symbols. ASCII bridges the gap
between human language and machine language. It assigns a unique number to each
character so that the computer can process and display text correctly.
How does ASCII work?
The ASCII system uses 7 bits to represent characters. With 7 bits, you can create 128 unique
combinations of 0s and 1s. This is enough to represent:
1. Uppercase letters: A to Z (65 to 90)
2. Lowercase letters: a to z (97 to 122)
3. Numbers: 0 to 9 (48 to 57)
4. Special characters: !, @, #, $, etc.
5. Control characters: These are non-printable characters like a newline (\n) or tab (\t).
Extended ASCII
Later, an extended version of ASCII was developed, which uses 8 bits. This provides 256
combinations, adding extra characters like symbols from other languages (e.g., accented
letters like é).
11
Easy2Siksha
Example of ASCII Table
Here’s a small sample of ASCII codes:
Character
Binary Representation
A
1000001
B
1000010
a
1100001
0
0110000
$
0100100
Analogy
Think of ASCII as a dictionary. Just as a dictionary maps words to their meanings, ASCII maps
characters to their corresponding numbers.
Practical Example in C Programming
Let’s say you want to display the ASCII value of a character in a C program:
#include <stdio.h>
int main() {
char ch = 'A';
printf("The ASCII value of %c is %d\n", ch, ch);
return 0;
}
Output:
The ASCII value of A is 65
12
Easy2Siksha
(b) Algorithm and Its Characteristics
What is an Algorithm?
An algorithm is a step-by-step set of instructions designed to solve a specific problem or
perform a task. Think of it as a recipe in cooking. Just as a recipe tells you how to prepare a
dish step by step, an algorithm explains how to solve a problem in a logical sequence.
Example of an Algorithm
Let’s take the example of preparing a cup of tea:
1. Boil water.
2. Add tea leaves.
3. Add sugar.
4. Add milk.
5. Stir and serve.
This sequence of steps ensures you successfully prepare tea.
Similarly, in programming, an algorithm helps solve problems, like finding the largest
number in a list or sorting a set of names alphabetically.
Characteristics of a Good Algorithm
For an algorithm to be effective, it must have the following characteristics:
1. Finiteness
o An algorithm must always terminate after a finite number of steps. It cannot
go on forever.
o Example: If you’re adding two numbers, you will eventually get the result and
stop.
2. Definiteness
o Each step of the algorithm must be clear and unambiguous. There should be
no confusion about what to do next.
o Example: In the tea-making example, "Add sugar" is a definite step. It doesn’t
leave room for interpretation.
3. Input
o An algorithm must accept some input values to work. Without input, it has
nothing to process.
o Example: To calculate the sum of two numbers, you need two inputs (the
numbers).
13
Easy2Siksha
4. Output
o An algorithm must produce at least one output as a result. This is the solution
to the problem.
o Example: After adding two numbers, the sum is the output.
5. Effectiveness
o The steps of the algorithm must be simple enough to be performed in a
reasonable amount of time.
o Example: Adding two numbers is an effective step because it can be done
quickly.
6. Generality
o A good algorithm should solve not just one specific problem but a range of
similar problems.
o Example: An algorithm to add two numbers should work for any pair of
numbers, not just specific ones like 2 and 3.
Analogy
Think of an algorithm as a travel plan. If you want to go from City A to City B:
1. You decide your starting point (input).
2. You follow a set of directions (steps).
3. You reach your destination (output).
4. The plan is clear, finite, and can be reused by others traveling between the same
cities.
Algorithms in C Programming
Here’s an example of an algorithm to find the largest of three numbers:
Steps:
1. Start.
2. Input three numbers: a, b, and c.
3. Compare a with b and c.
o If a > b and a > c, then a is the largest.
4. Compare b with c.
o If b > c, then b is the largest.
5. Otherwise, c is the largest.
6. End.
14
Easy2Siksha
Code Implementation:
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b && a > c) {
printf("The largest number is %d\n", a);
} else if (b > c) {
printf("The largest number is %d\n", b);
} else {
printf("The largest number is %d\n", c);
}
return 0;
}
Output Example:
If the input is 3 7 5, the output will be:
The largest number is 7
Conclusion
ASCII helps computers understand text by converting characters into numbers. It’s
like a translator between humans and machines.
Algorithms are step-by-step instructions to solve problems, just like a recipe in
cooking or a travel plan for reaching your destination.
By combining these concepts in programming, you can create efficient and effective
solutions for a wide range of problems!
15
Easy2Siksha
SECTION-B
3. (a) What is meant by hierarachy of operators ? Provide a brief outline of all operators
supported by C language along with their hierarchy within expressions and suitable
examples.
(b) Why C language is named so? Discuss its origin and provide the general structure of
C language program detailing our every construct in it.
Ans: Hierarchy of Operators in C
In programming, the term hierarchy of operators refers to the order of precedence that
operators follow in expressions. When there are multiple operators in an expression, the
precedence determines which operator gets executed first. Alongside precedence,
associativity determines the direction of execution for operators with the same precedence
(either left-to-right or right-to-left).
Think of it like solving a math problem: in the expression 3 + 5 * 2, the multiplication (*)
happens first because it has higher precedence than addition (+). Similarly, in C, operators
have predefined precedence and associativity to ensure expressions are evaluated correctly.
Categories of Operators in C
C supports a wide range of operators that are divided into the following categories:
1. Arithmetic Operators
2. Relational (Comparison) Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and Decrement Operators
7. Conditional (Ternary) Operator
8. Comma Operator
9. Sizeof Operator
10. Pointer Operators
11. Special Operators
Hierarchy of Operators in C
Below is a detailed outline of all operators in C along with their hierarchy (precedence and
associativity).
16
Easy2Siksha
1. Highest Precedence Operators
Parentheses ( ): Parentheses are used to explicitly group expressions or alter
precedence.
o Example:
int result = (3 + 5) * 2; // Adds 3 and 5 first, then multiplies by 2
2. Unary Operators
Operators: + (unary plus), - (unary minus), ! (logical NOT), ~ (bitwise NOT), ++
(increment), -- (decrement), & (address-of), * (dereference), sizeof
Associativity: Right-to-left
Description:
o Unary Minus (-): Negates a number.
o Increment/Decrement (++, --): Adds or subtracts 1.
Prefix: Changes the value before use.
Postfix: Changes the value after use.
Example:
int x = 5;
int y = ++x; // Prefix: x becomes 6, then y is assigned 6
int z = x--; // Postfix: z is assigned 6, then x becomes 5
3. Multiplicative Operators
Operators: * (multiplication), / (division), % (modulus)
Associativity: Left-to-right
Example:
int result = 10 * 2 / 5; // Evaluates left-to-right as (10 * 2) / 5 = 4
4. Additive Operators
Operators: + (addition), - (subtraction)
Associativity: Left-to-right
Example:
int result = 10 + 5 - 3; // Evaluates as (10 + 5) - 3 = 12
5. Shift Operators
Operators: << (left shift), >> (right shift)
17
Easy2Siksha
Associativity: Left-to-right
Description: Used for shifting bits in numbers.
Example:
int result = 8 << 1; // Left shifts 8 by 1 bit, result is 16
6. Relational Operators
Operators: <, <=, >, >=
Associativity: Left-to-right
Example:
int isSmaller = 5 < 10; // Evaluates to 1 (true) because 5 is less than 10
7. Equality Operators
Operators: == (equal to), != (not equal to)
Associativity: Left-to-right
Example:
int isEqual = (5 == 5); // Evaluates to 1 (true)
int isNotEqual = (5 != 3); // Evaluates to 1 (true)
8. Bitwise AND
Operator: &
Associativity: Left-to-right
Example:
int result = 5 & 3; // Performs bitwise AND, result is 1
9. Bitwise XOR and OR
Operators: ^ (XOR), | (OR)
Associativity: Left-to-right
Example:
int result = 5 ^ 3; // XOR: 5 (101) ^ 3 (011) = 6 (110)
10. Logical AND and OR
Operators: && (AND), || (OR)
Associativity: Left-to-right
Description:
18
Easy2Siksha
o &&: True if both operands are true.
o ||: True if at least one operand is true.
Example:
int result = (5 > 3) && (10 > 5); // True && True = 1
11. Conditional Operator (Ternary)
Operator: ? :
Associativity: Right-to-left
Description: A shorthand for if-else.
Example:
int max = (5 > 3) ? 5 : 3; // If 5 > 3 is true, max is assigned 5, otherwise 3
12. Assignment Operators
Operators: =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=
Associativity: Right-to-left
Description: Used to assign values to variables.
Example:
int x = 5;
x += 3; // x = x + 3; now x is 8
13. Comma Operator
Operator: ,
Associativity: Left-to-right
Description: Evaluates multiple expressions and returns the last one.
Example:
int x, y;
x = (y = 3, y + 2); // y = 3, then x = y + 2 = 5
Rules of Precedence and Associativity
1. Operators with higher precedence are executed before those with lower
precedence.
2. When two operators have the same precedence, associativity decides the order of
evaluation.
19
Easy2Siksha
Simplified Example
Consider this complex expression:
int result = 10 + 5 * 2 > 15 && 20 / 5 == 4;
Step-by-step Evaluation:
1. Multiplication (*) and Division (/):
o 5 * 2 = 10
o 20 / 5 = 4
2. Addition (+):
o 10 + 10 = 20
3. Relational (>, ==):
o 20 > 15 = 1 (true)
o 4 == 4 = 1 (true)
4. Logical AND (&&):
o 1 && 1 = 1
Final result: 1 (true).
Conclusion
Understanding the hierarchy of operators is essential for writing clear and accurate code. By
knowing the precedence and associativity, you can predict how expressions will be
evaluated and avoid logical errors in your programs. Use parentheses ( ) to group parts of
expressions if you're unsure about the operator hierarchyit not only clarifies the code but
also ensures the correct order of execution.
(ii) Why is the ‘C’ Language Named So?
The name "C" for the programming language has an interesting and straightforward origin.
It is called "C" because it was developed as an improvement to an earlier programming
language called "B." The "B" language itself was based on a language called BCPL (Basic
Combined Programming Language), which was designed for writing system software.
Dennis Ritchie developed the C language in the early 1970s at Bell Laboratories. It was
created mainly to develop the Unix operating system, which is still widely used in the tech
world. C was a step forward in programming because it introduced features like better
control over computer hardware and more efficiency, making it very suitable for system-
level programming.
20
Easy2Siksha
The name "C" reflects its position as a successor to "B" and symbolizes its evolution from
earlier languages.
Origin of C Language
To understand the origin of C, let's trace its history briefly:
1. BCPL (1966): Martin Richards developed BCPL as a simple and powerful language for
writing compilers.
2. B Language (1969): Ken Thompson simplified BCPL to create the "B" language,
mainly to develop the Unix operating system on the PDP-7 computer.
3. C Language (1972): Dennis Ritchie improved the B language by adding features like
data types and structures. This enhanced flexibility and efficiency, leading to the
creation of C.
C quickly became popular because of its simplicity, portability (ability to work on different
systems), and ability to provide low-level access to hardware while remaining readable.
General Structure of a C Program
A C program has a well-defined structure. Think of it as a recipe for cookingit has specific
steps, ingredients (data), and tools (functions) to achieve a task. Let's explore the structure
step-by-step.
1. Structure of a C Program
A basic C program generally includes the following components:
#include <stdio.h> // Preprocessor Directive
int main() { // Main Function
// Variable Declaration
int num;
// Statements
num = 5;
printf("The value of num is: %d", num);
return 0; // Return Statement
}
21
Easy2Siksha
Let’s break it down:
2. Explanation of Constructs
1. Preprocessor Directives
These are lines that begin with # and are used to include libraries or files before
compilation.
o Example: #include <stdio.h> includes the standard input/output library,
which allows you to use functions like printf() and scanf().
Think of it as bringing tools into your toolbox before starting the job. Without this step, you
wouldn’t have access to many essential tools in C.
2. Main Function (int main())
o This is where the program starts execution. Every C program must have one
main() function.
o It is like the entry point of a house. All activities (instructions) begin here.
3. Variable Declaration
o Variables are used to store data.
o Example: int num; declares a variable named num of type int (integer).
o You can think of variables as containers that hold information, such as
numbers or text, that the program needs to work with.
4. Statements and Expressions
o These are the instructions you write to perform tasks.
o Example: num = 5; assigns the value 5 to the variable num.
o Another example: printf("The value of num is: %d", num); prints the value of
num on the screen.
5. Return Statement (return 0;)
o This ends the program and sends a value (usually 0) back to the operating
system.
o Think of it as the program saying, "I’ve finished my job successfully!"
Detailed Components of a C Program
Let’s explore these concepts in more detail with analogies and examples.
Preprocessor Directive
Imagine you’re about to cook a meal. Before you start, you gather your utensils (e.g., a
knife, pan, etc.) and ingredients. Similarly, in a C program, preprocessor directives like
#include bring in libraries that provide essential tools.
22
Easy2Siksha
Without #include <stdio.h>, you cannot use the printf() function to display messages.
Variables and Data Types
Variables are like labeled jars in a kitchen where you store ingredients (e.g., sugar, salt). In C,
you must declare these jars before use and specify the type of ingredient they will hold (e.g.,
int for integers, float for decimals, char for characters).
Example:
int age = 25; // 'age' is a jar that stores the integer value 25.
Functions
Functions are like recipes. Each recipe has steps to achieve a particular goal (e.g., bake a
cake). In C, a function like main() is the main recipe, while you can also create additional
recipes (functions) for specific tasks.
Example:
void greet() {
printf("Hello, World!");
}
Control Statements
Control statements are decision-makers. Think of them as the if-else situations in life.
Example:
if (age >= 18) {
printf("You are eligible to vote.");
} else {
printf("You are not eligible to vote.");
}
Loops
Loops are repetitive tasks, like stirring soup in a pot until it boils.
Example:
for (int i = 1; i <= 5; i++) {
printf("%d\n", i); // Prints numbers 1 to 5
}
23
Easy2Siksha
Comments
Comments are notes written in the program for the programmer’s understanding. The
computer ignores them.
Example:
// This is a single-line comment.
/* This is a multi-line comment. */
Full Example Program
Let’s write a complete program using all the constructs:
#include <stdio.h> // Include library
int main() { // Main function
int num; // Declare variable
printf("Enter a number: ");
scanf("%d", &num); // Input from user
if (num % 2 == 0) { // Check if the number is even
printf("%d is an even number.\n", num);
} else {
printf("%d is an odd number.\n", num);
}
return 0; // End program
}
Conclusion
The C language is powerful, versatile, and forms the foundation for many modern
programming languages. Its structured approach, simplicity, and efficiency make it a favorite
for beginners and experts alike. By understanding the general structure and constructs of a
C program, you can start writing your own programs and explore the world of coding step-
by-step.
24
Easy2Siksha
4. Differentiate between the following:
(a) printf() and scanf()
(b) Formated and Unformatted Console I/O functions.
Ans: Difference between printf() and scanf()
Introduction
The C programming language provides several functions for Input/Output (I/O) operations.
Among these, printf() and scanf() are the two most common functions used to display
information to the user and take input from the user, respectively. These functions are part
of the stdio.h (Standard Input/Output Header) file in C. Though they appear simple, they
play a significant role in enabling communication between a program and its user.
(a) Difference Between printf() and scanf()
Criteria
printf()
scanf()
Purpose
printf() is used to display output on
the screen.
scanf() is used to take input from the
user.
Direction of
Data
Sends (writes) data from the
program to the output screen.
Receives (reads) data from the user
into variables.
Function Type
It is an output function.
It is an input function.
Syntax
printf("format string", arguments);
scanf("format string", &variables);
Format
Specifiers
Used to format output data.
Examples: %d, %f, %c, %s.
Used to specify the format of input
data. Examples: %d, %f, %c, %s.
User Interaction
Does not require user interaction
to execute.
Requires user input to proceed.
Use of
Ampersand (&)
Not required while displaying
variables.
Required with variables to store input
data (except strings).
25
Easy2Siksha
Detailed Explanation of printf()
1. Purpose of printf():
o The printf() function is used to display (print) output on the console (screen).
o It is a way for the program to communicate information to the user.
2. Syntax:
printf("format string", arguments);
o format string contains the text and format specifiers like %d (integer), %f
(floating point), %c (character), %s (string), etc.
o arguments are the variables or values to display.
Example:
3. #include <stdio.h>
4. int main() {
5. int age = 20;
6. float marks = 85.5;
7. char grade = 'A';
8.
9. printf("Age: %d\n", age); // Prints an integer
10. printf("Marks: %.2f\n", marks); // Prints a float with 2 decimal points
11. printf("Grade: %c\n", grade); // Prints a character
12.
13. return 0;
}
Output:
Age: 20
Marks: 85.50
Grade: A
o The format specifiers (%d, %.2f, %c) are replaced with the values of variables.
14. Key Notes:
o You do not need to use & (ampersand) with variables in printf().
o Special characters like \n are used to insert newlines.
26
Easy2Siksha
o Format specifiers allow you to control how the output appears on the screen.
Detailed Explanation of scanf()
1. Purpose of scanf():
o The scanf() function is used to take input from the user during the execution
of a program.
o It is a way for the program to receive data.
2. Syntax:
scanf("format string", &variables);
o format string specifies the type of input data (e.g., %d, %f, %c, %s).
o &variables tells the compiler where to store the input data. The &
(ampersand) is used to access the address of a variable.
3. Example:
4. #include <stdio.h>
5. int main() {
6. int age;
7. float marks;
8. char grade;
9.
10. printf("Enter your age: ");
11. scanf("%d", &age); // Reads an integer input
12.
13. printf("Enter your marks: ");
14. scanf("%f", &marks); // Reads a float input
15.
16. printf("Enter your grade: ");
17. scanf(" %c", &grade); // Reads a character input
18.
19. printf("You entered: \n");
20. printf("Age: %d\n", age);
21. printf("Marks: %.2f\n", marks);
27
Easy2Siksha
22. printf("Grade: %c\n", grade);
23.
24. return 0;
}
Input:
Enter your age: 20
Enter your marks: 85.5
Enter your grade: A
Output:
You entered:
Age: 20
Marks: 85.50
Grade: A
25. Key Notes:
o You must use & before the variable names in scanf() to tell the compiler
where to store the input.
o If you miss the &, the program will not work correctly.
o When reading character inputs, a space before %c (" %c") is necessary to
ignore any leftover newline characters.
(b) Difference Between Formatted and Unformatted Console I/O Functions
C programming language supports two types of Input/Output (I/O) functions:
1. Formatted I/O Functions
2. Unformatted I/O Functions
Criteria
Formatted I/O Functions
Unformatted I/O Functions
Definition
These functions use format specifiers
to input/output data in a specified
format.
These functions directly
input/output data without any
format specifiers.
Examples
printf() and scanf()
getchar(), putchar(), gets(), puts()
28
Easy2Siksha
Data Handling
Allows control over the format and
type of data.
Deals with raw data, usually
character-by-character or string
input/output.
Use of Format
Specifiers
Yes, format specifiers like %d, %f, %c,
%s are required.
No format specifiers are used.
Complexity
More complex but flexible.
Simple but limited.
Formatted I/O Functions
Formatted I/O functions allow the user to specify the format of the input or output data
using format specifiers like %d, %f, %c, %s, etc.
Examples:
printf() for formatted output
scanf() for formatted input
Advantages:
Provides flexibility to display or read data in various formats (e.g., integers, floats,
strings).
Allows precision control for floating-point numbers (e.g., %.2f for two decimal
places).
Example:
#include <stdio.h>
int main() {
int a;
printf("Enter a number: ");
scanf("%d", &a);
printf("You entered: %d\n", a);
return 0;
}
Unformatted I/O Functions
Unformatted I/O functions directly input or output raw data without using format specifiers.
29
Easy2Siksha
Examples:
getchar() to read a single character
putchar() to print a single character
gets() to read a string
puts() to print a string
Advantages:
Simple and easy to use for basic input/output operations.
Example:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Reads a single character
printf("You entered: ");
putchar(ch); // Prints a single character
return 0;
}
Input:
A
Output:
You entered: A
Conclusion
In summary:
printf() is used to display output, while scanf() is used to take input.
Formatted I/O functions (printf, scanf) use format specifiers to control input/output,
while unformatted I/O functions (`
30
Easy2Siksha
SECTION-C
5. (a) What is an array? What are different types of array ? How do you create and use
these arrays? Explain.
(b) How do you define a String? What are String functions? How do you create array of
strings? Explain.
Ans: What is an Array?
An array is a collection of similar types of data stored at contiguous memory locations. Think
of an array like a row of lockers or a series of boxes lined up one after another. Each locker
(or box) can hold a value, and you can easily identify each locker using a number, called its
index or position.
In simpler terms, an array helps you store multiple values of the same type (e.g., all integers,
all characters, etc.) using a single variable name. Instead of creating separate variables for
each value, you can use an array to organize them efficiently.
For example:
If you need to store 5 marks of a student, instead of writing:
int mark1, mark2, mark3, mark4, mark5;
You can use an array like this:
int marks[5]; // An array to store 5 integers.
Why Use Arrays?
1. Efficient Memory Management: Arrays help you save memory and reduce code
length.
2. Organized Storage: It is easy to store and access multiple values.
3. Better Performance: Arrays allow fast data processing, especially in loops.
Types of Arrays
There are two main types of arrays in C:
1. One-Dimensional Array (1D Array)
2. Two-Dimensional Array (2D Array)
Let's discuss each type in detail.
1. One-Dimensional Array
A 1D array is like a straight line of lockers, where each locker is used to store a single value.
You can think of it as a list of values.
Declaration of a 1D Array
31
Easy2Siksha
To create a 1D array in C, you follow this format:
data_type array_name[size];
data_type: The type of values you want to store (e.g., int, float, char).
array_name: The name you give to your array.
size: The number of elements (or values) the array can hold.
Example:
int numbers[5]; // Creates an array of 5 integers.
Here:
int means the array can store integer values.
numbers is the name of the array.
[5] means it can store 5 elements.
Accessing Elements in a 1D Array
You can access each element of the array using an index.
The index always starts from 0.
So, the first element has an index of 0, the second element has an index of 1, and so
on.
Example with Initialization:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Initializing the array
// Accessing and printing array elements
printf("First element: %d\n", numbers[0]);
printf("Second element: %d\n", numbers[1]);
printf("Third element: %d\n", numbers[2]);
printf("Fourth element: %d\n", numbers[3]);
printf("Fifth element: %d\n", numbers[4]);
return 0;
}
32
Easy2Siksha
Output:
First element: 10
Second element: 20
Third element: 30
Fourth element: 40
Fifth element: 50
Using Loops with a 1D Array
Instead of printing each element one by one, you can use a loop to access all the elements.
#include <stdio.h>
int main() {
int marks[5] = {85, 90, 78, 92, 88}; // Array of 5 integers
// Printing all elements using a loop
for (int i = 0; i < 5; i++) {
printf("Mark %d: %d\n", i + 1, marks[i]);
}
return 0;
}
Key Points About 1D Arrays:
1. All elements in a 1D array are of the same data type.
2. The size of the array must be specified while declaring it.
3. Array indexing starts from 0.
2. Two-Dimensional Array
A 2D array is like a table with rows and columns. It is used to store data in a grid or matrix
form. You can think of it as a set of lockers arranged in rows and columns.
Declaration of a 2D Array
To create a 2D array in C, you follow this format:
data_type array_name[rows][columns];
rows: Number of rows in the table.
33
Easy2Siksha
columns: Number of columns in the table.
Example:
int matrix[2][3]; // Creates a 2D array with 2 rows and 3 columns.
Here:
int means the array can store integer values.
matrix is the name of the array.
[2][3] means there are 2 rows and 3 columns.
Initializing a 2D Array
You can initialize a 2D array like this:
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
This means:
Row 1 → 1, 2, 3
Row 2 → 4, 5, 6
Accessing Elements in a 2D Array
To access elements, you use two indices:
The first index represents the row number.
The second index represents the column number.
Example:
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
// Accessing and printing elements
printf("First row, second column: %d\n", matrix[0][1]); // Output: 2
printf("Second row, third column: %d\n", matrix[1][2]); // Output: 6
return 0;
}
34
Easy2Siksha
Using Loops with a 2D Array
To print all elements of a 2D array, you can use nested loops (a loop inside another loop):
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
// Printing all elements of the 2D array
for (int i = 0; i < 2; i++) { // Loop for rows
for (int j = 0; j < 3; j++) { // Loop for columns
printf("%d ", matrix[i][j]);
}
printf("\n"); // Move to the next line after printing a row
}
return 0;
}
Output:
1 2 3
4 5 6
Summary of Key Points
1. Array: A collection of similar types of values stored together.
2. 1D Array: Stores data in a single row (like a list).
3. 2D Array: Stores data in rows and columns (like a table).
4. Access: Use indices to access elements (starting from 0).
5. Loops: Loops help efficiently access and manipulate array elements.
Analogy:
If variables are like individual lockers in different places, arrays are like lockers neatly
arranged in rows and columns in a single location, making it easy to store, organize, and
access values efficiently.
35
Easy2Siksha
This explanation simplifies the concept of arrays, covers their types, and includes relevant
examples to ensure clarity.
(ii) What is a String in C?
In C programming, a string is a sequence of characters that ends with a special character
called the null character (\0). This null character is automatically added at the end of the
string when it is created. It acts as a terminator, indicating where the string ends.
Think of a string as a word or a sentence made up of individual letters (characters). For
example:
The word "hello" is a string.
The sentence "This is a string" is also a string.
In C, strings are not a built-in data type like integers or floats. Instead, strings are stored in
an array of characters. This means that a string is simply a collection of characters arranged
one after another in memory.
For example:
char myString[] = "Hello";
Here:
char indicates that the array contains characters.
myString is the name of the array.
"Hello" is the sequence of characters stored in the array, including the null character
\0 at the end.
How Strings are Stored in C
When you store a string "Hello" in memory, it looks like this:
Index
0
1
2
3
4
5
Value
H
e
l
l
o
0
The indices (0, 1, 2, etc.) are positions in the character array.
The null character \0 is placed at the end to mark the end of the string.
String Functions in C
To make working with strings easier, the C programming language provides several built-in
functions that allow you to perform common operations on strings. These functions are
defined in the string.h header file.
36
Easy2Siksha
Here are some important string functions, their uses, and examples:
1. strlen(): To Find the Length of a String
The strlen() function calculates the length of a string (the number of characters before the
null character \0).
Syntax:
int strlen(char *str);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("The length of the string is: %d", strlen(str));
return 0;
}
Output:
csharp
The length of the string is: 5
Here, the function ignores the null character at the end of the string.
2. strcpy(): To Copy a String
The strcpy() function copies the content of one string into another.
Syntax:
char *strcpy(char *destination, const char *source);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello";
char destination[20];
37
Easy2Siksha
strcpy(destination, source); // Copies "Hello" into destination
printf("Copied string: %s", destination);
return 0;
}
Output:
Copied string: Hello
3. strcat(): To Concatenate (Join) Two Strings
The strcat() function joins two strings together. It appends the second string to the end of
the first string.
Syntax:
char *strcat(char *destination, const char *source);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello ";
char str2[] = "World!"
strcat(str1, str2); // Appends str2 to str1
printf("Concatenated string: %s", str1);
return 0;
}
Output:
Concatenated string: Hello World!
4. strcmp(): To Compare Two Strings
The strcmp() function compares two strings character by character. It returns:
0 if the strings are equal,
A positive value if the first string is greater,
A negative value if the first string is smaller.
38
Easy2Siksha
Syntax:
int strcmp(const char *str1, const char *str2);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0)
printf("Strings are equal.");
else
printf("Strings are not equal.");
return 0;
}
Output:
Strings are not equal.
5. strrev(): To Reverse a String
The strrev() function reverses a string. Note that this is not part of the standard library but is
available in some compilers.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
39
Easy2Siksha
strrev(str);
printf("Reversed string: %s", str);
return 0;
}
Output:
Reversed string: olleH
How to Create an Array of Strings in C
An array of strings is an array where each element is a string. This is useful when you want
to store multiple strings.
Example:
Imagine you are creating a program to store the names of five friends. You can use an array
of strings.
Here’s how to create an array of strings:
Example Code:
#include <stdio.h>
int main() {
// Array of strings
char friends[5][20] = {
"Alice",
"Bob",
"Charlie",
"David",
"Eve"
};
// Printing all the strings
for (int i = 0; i < 5; i++) {
printf("Friend %d: %s\n", i + 1, friends[i]);
}
40
Easy2Siksha
return 0;
}
Explanation:
1. char friends[5][20] means:
o There are 5 strings in the array.
o Each string can store up to 19 characters + 1 null character.
2. The strings are stored one after another in memory.
3. The for loop prints each string one by one.
Output:
Friend 1: Alice
Friend 2: Bob
Friend 3: Charlie
Friend 4: David
Friend 5: Eve
Analogy to Understand Strings and Arrays of Strings
Think of a string as a single word written on a piece of paper.
The null character \0 is like a period . that marks the end of the word.
Now, imagine an array of strings as a book containing multiple words or sentences.
Each page of the book represents one string (a line of words).
In C:
String = A single line of text (array of characters).
Array of Strings = A group of lines of text (a 2D array of characters).
Conclusion
In C programming:
1. A string is a sequence of characters terminated by a null character \0.
2. String functions like strlen(), strcpy(), strcat(), and strcmp() help you perform
operations like finding length, copying, concatenating, and comparing strings.
3. An array of strings allows you to store multiple strings, which is useful when dealing
with collections of text data.
41
Easy2Siksha
6. Differentiate between the following:
(a) for and do-while loops
(b) switch and if-else-if statements.
Ans: Differentiating Between:
(a) For Loop and Do-While Loop
Both for and do-while loops are used to repeat a set of instructions, but they differ in how
they execute and handle conditions. Let's explore their differences in a detailed and easy-to-
understand way.
1. Execution Flow
For Loop:
o The condition is checked before the loop starts.
o If the condition is false, the loop will not execute at all.
o It is a pre-check loop.
Example:
for (int i = 1; i <= 5; i++) {
printf("Value of i: %d\n", i);
}
Explanation:
o The loop starts by initializing i to 1.
o It checks if i <= 5. If true, it runs the block of code.
o After running the code, it increases i by 1 and repeats the process until the
condition becomes false.
Do-While Loop:
o The loop executes the block of code at least once, regardless of the
condition.
o The condition is checked after the block of code has been executed.
o It is a post-check loop.
Example:
int i = 1;
do {
42
Easy2Siksha
printf("Value of i: %d\n", i);
i++;
} while (i <= 5);
Explanation:
o The loop runs the block of code and prints the value of i.
o Only after executing the code does it check if i <= 5.
o This ensures that the code inside the loop is executed at least once, even if
the condition is false initially.
2. Key Differences
Feature
For Loop
Do-While Loop
Condition
Checking
Before entering the loop.
After executing the loop.
Guaranteed
Execution
Not guaranteed (if the condition is
false initially).
Executes at least once.
Usage
Preferred when the number of
iterations is known.
Preferred when the loop must run
at least once.
3. Analogy
For Loop: Think of it as a strict teacher checking your homework before letting you
into class. If you haven't done your homework, you don't enter (loop doesn't
execute).
Do-While Loop: Think of it as a relaxed teacher who lets you into class first and then
checks your homework. You always get in at least once!
4. Real-Life Example
Imagine a digital lock:
For Loop: It checks if you have entered the correct password before unlocking. If
your password is wrong, the lock doesn't open.
43
Easy2Siksha
Do-While Loop: The lock opens the door once, and only after that does it verify if the
password was correct. Even a wrong password lets you in initially (though it's a bad
idea for security!).
5. Best Use Cases
Use for loop when you know how many times the loop should run (like counting
from 1 to 10).
Use do-while loop when you want to ensure the code inside the loop runs at least
once, regardless of the condition (e.g., prompting a user for input until they provide
a valid response).
(b) Switch and If-Else-If Statements
Both switch and if-else-if are used to execute different blocks of code based on a condition,
but they work differently. Let's explore their differences in detail.
1. Execution Flow
Switch Statement:
o Used when you have multiple fixed values to compare against a single
variable.
o It directly jumps to the matching case and executes the associated block of
code.
Example:
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
44
Easy2Siksha
}
Explanation:
o The variable day is compared to each case.
o When it matches case 3, it prints "Wednesday".
o The break statement ensures the program exits the switch block after
executing the matching case.
If-Else-If Statement:
o Used when you need to test multiple conditions.
o The conditions can involve complex expressions, not just fixed values.
Example:
int marks = 85;
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else if (marks >= 50) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
Explanation:
o The conditions are checked one by one.
o When marks >= 75 is true, it prints "Grade: B" and skips the rest.
2. Key Differences
Feature
Switch Statement
If-Else-If Statement
Comparison
Type
Compares a single variable against
fixed values.
Evaluates multiple conditions.
45
Easy2Siksha
Feature
Switch Statement
If-Else-If Statement
Complexity
Limited to equality checks.
Handles complex conditions.
Default Case
Executes when no match is found.
Executes the else block if no
condition is true.
Execution
Speed
Faster for fixed values (direct jump).
Slower for many conditions (checks
one by one).
3. Analogy
Switch Statement: Think of it as a vending machine. You press a button (e.g., 1 for
soda, 2 for chips), and the machine directly gives you the selected item (no further
checks needed).
If-Else-If Statement: Think of it as a restaurant menu. You tell the waiter your
preference ("I want something spicy"), and they evaluate different dishes to match
your request.
4. Real-Life Example
Imagine selecting a mode of transport based on distance:
Switch Statement: You choose a transport mode based on a fixed distance range
(e.g., 0-5 km for walking, 5-10 km for cycling, 10+ km for a car).
If-Else-If Statement: You evaluate not just the distance but also other conditions like
weather, time, or budget to decide the best transport mode.
5. Best Use Cases
Use switch when you have a fixed set of possible values (e.g., days of the week,
menu options).
Use if-else-if when you need to evaluate complex or overlapping conditions (e.g.,
determining grades, eligibility for a loan).
46
Easy2Siksha
Summary Table
Feature
For Loop
Do-While Loop
Switch Statement
If-Else-If Statement
Condition
Checking
Before
execution.
After execution.
Compares fixed
values.
Evaluates complex
conditions.
Execution
Guarantee
No
Yes, at least
once.
Executes matching
case.
Executes the first
true block.
Best For
Known
iterations.
At least one
execution.
Fixed comparisons.
Complex decisions.
SECTION-D
7. Explain the following:
(a) Union and Structure
(b) Scope and lifetime of a variable
I Recursion.
Ans: Understanding Union and Structure, Scope and Lifetime of a Variable, and Recursion
When studying computer programming in a course like B.A. 2nd semester, you encounter
many important concepts. Three of these are Union and Structure, Scope and Lifetime of a
Variable, and Recursion. Let's break these down into simple terms so they are easy to
understand, complete with examples and analogies.
(a) Union and Structure
1. What is a Structure?
A structure is a way to group different types of variables together into one unit. Think of a
structure like a toolbox. A toolbox can hold different tools, like a hammer, screwdriver, and
wrench, each serving a unique purpose. Similarly, a structure can hold variables of different
types, such as integers, floats, and strings.
Example:
Imagine you want to store details about a book:
47
Easy2Siksha
The title (a string),
The price (a float), and
The number of pages (an integer).
You can use a structure to group these pieces of information:
struct Book {
char title[50];
float price;
int pages;
};
Here, Book is the structure, and it combines all the details of a book into one unit. You can
now use this structure to create many books:
struct Book myBook;
myBook.price = 350.50;
myBook.pages = 200;
strcpy(myBook.title, "Programming in C");
2. What is a Union?
A union is similar to a structure because it groups variables together, but there is one key
difference: a union shares the same memory space for all its members. This means that at
any given time, a union can only store a value for one of its members.
Think of a union like a one-room apartment shared by different people. Only one person can
use the space at a time, unlike a structure, where everyone has their own room.
Example:
Suppose you want to store data that could either be an integer, a float, or a character, but
never all three at once. You can use a union:
union Data {
int i;
float f;
char c;
};
Now, when you use this union:
48
Easy2Siksha
union Data myData;
myData.i = 10; // Store an integer
printf("Integer: %d\n", myData.i);
myData.f = 20.5; // Store a float (overwrites the integer)
printf("Float: %.2f\n", myData.f);
When myData.f is assigned, it overwrites myData.i because they share the same memory.
That’s why unions are useful when you want to save memory and you know you’ll only need
one type of value at a time.
Key Differences Between Structure and Union:
Feature
Structure
Union
Memory
Usage
Each member has its own memory.
All members share the same memory.
Access
All members can be accessed
simultaneously.
Only one member can hold a value at a
time.
Use Case
Used for storing multiple types of
data simultaneously.
Used when only one type of data is
needed at a time.
(b) Scope and Lifetime of a Variable
When you write a program, variables have a scope and a lifetime, which determine where
and how long the variable can be used.
49
Easy2Siksha
1. Scope of a Variable:
The scope of a variable defines where in the program you can access or use it. It’s like a
boundary. There are three main types of scope:
(i) Global Scope:
These variables are declared outside all functions.
They can be accessed anywhere in the program.
Think of global variables as something like a public park; everyone can access it.
Example:
int globalVar = 10; // Global variable
void func1() {
printf("Global variable: %d\n", globalVar);
}
void func2() {
globalVar += 5;
printf("Global variable updated: %d\n", globalVar);
}
(ii) Local Scope:
These variables are declared inside a function or block.
They can only be accessed within that function.
Think of a local variable as a private room in your house; only you can use it.
Example:
void func() {
int localVar = 20; // Local variable
printf("Local variable: %d\n", localVar);
}
// localVar cannot be accessed outside this function.
(iii) Block Scope:
These variables are declared inside loops, if statements, or any other block of code.
50
Easy2Siksha
Their scope is limited to that block.
Example:
if (1) {
int blockVar = 30; // Block-scoped variable
printf("Block variable: %d\n", blockVar);
}
// blockVar cannot be accessed outside the 'if' block.
2. Lifetime of a Variable:
The lifetime of a variable refers to how long the variable exists in memory during the
program's execution.
(i) Static Lifetime:
These variables exist for the entire duration of the program.
They retain their values even after the function ends.
Declared using the static keyword.
Example:
void staticExample() {
static int count = 0; // Static variable
count++;
printf("Count: %d\n", count);
}
(ii) Automatic Lifetime:
These variables are created when a function is called and destroyed when the
function ends.
Most local variables have an automatic lifetime.
Example:
void autoExample() {
int temp = 5; // Automatic variable
printf("Temporary value: %d\n", temp);
}
51
Easy2Siksha
(c) Recursion
1. What is Recursion?
Recursion is when a function calls itself to solve a smaller part of a problem. It’s like standing
between two mirrors and seeing infinite reflections. Each reflection is a smaller version of
the original.
Recursion is useful for solving problems that can be broken into smaller, similar problems,
such as calculating factorials, Fibonacci numbers, or traversing a directory.
2. Key Components of Recursion:
Every recursive function must have:
1. Base Case: The condition that stops the recursion. Without it, the function will keep
calling itself indefinitely, causing an error.
2. Recursive Case: The part where the function calls itself with a smaller problem.
3. Example of Recursion:
(i) Calculating Factorial:
The factorial of a number n is the product of all positive integers less than or equal to n.
For example, 5! = 5 × 4 × 3 × 2 × 1.
Recursive function:
int factorial(int n) {
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive case
}
How it works:
1. factorial(5) calls factorial(4).
2. factorial(4) calls factorial(3), and so on.
3. When factorial(0) is reached, it returns 1.
4. The values are then multiplied as the recursion unwinds.
(ii) Fibonacci Sequence:
The Fibonacci sequence is a series where each number is the sum of the two preceding
ones: 0, 1, 1, 2, 3, 5, 8...
52
Easy2Siksha
Recursive function:
int fibonacci(int n) {
if (n == 0) // Base case
return 0;
else if (n == 1) // Base case
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
Analogy for Recursion:
Imagine you’re climbing a staircase. To reach the top:
1. First, you climb one step (base case).
2. Then, you keep repeating the process of taking one step (recursive case) until you
reach the top.
Advantages of Recursion:
Simplifies complex problems.
Makes code easier to read for problems like tree traversal or searching.
Disadvantages:
Can be inefficient for large inputs due to repeated calculations.
Uses more memory because of the function call stack.
By understanding Union and Structure, Scope and Lifetime of Variables, and Recursion, you
can write better and more efficient programs. These concepts are like building blocks for
many advanced programming topics.
8. Differentiate between the following:
(a) Call-by-value and call-by-reference
(b) Automatic, External and Static variables
I User Defined and Library Functions.
Ans: Differentiation Between Call-by-Value and Call-by-Reference
53
Easy2Siksha
Call-by-Value:
1. Definition: In this method, a copy of the actual value is passed to the function. Any
changes made inside the function do not affect the original value.
2. How It Works: Imagine you make a photocopy of a document (original value) and
write on the photocopy (function). The changes appear only on the photocopy, not
on the original document.
3. Characteristics:
o The actual value in the calling function remains unchanged.
o It is safe because the original data is not modified.
o Typically uses more memory since a duplicate copy of the data is created.
4. Example:
void modifyValue(int x) {
x = x + 10; // Only modifies the copy
}
int main() {
int num = 5;
modifyValue(num); // The value of num remains 5
return 0;
}
Here, num is passed as a copy, so the original value remains unchanged.
Call-by-Reference:
1. Definition: In this method, the actual memory address of the value is passed to the
function. Changes made inside the function affect the original value.
2. How It Works: Imagine you give someone a direct key to your house (original value).
Any changes they make in the house are permanent because they have access to the
real thing.
3. Characteristics:
o The original value can be modified.
o Memory is saved since no duplicate copy is created.
o Less secure because the original data can be altered.
54
Easy2Siksha
4. Example:
void modifyValue(int &x) {
x = x + 10; // Modifies the original value
}
int main() {
int num = 5;
modifyValue(num); // The value of num becomes 15
return 0;
}
Here, num is passed by reference, so the function modifies the original value.
Automatic, External, and Static Variables
Automatic Variables:
1. Definition: These variables are declared inside a function and exist only while the
function is running. They are created when the function starts and destroyed when
the function ends.
2. How It Works: Think of it like renting a car for a trip. Once the trip ends, you return
the car.
3. Characteristics:
o Default storage class in most programming languages.
o Their values are not retained between function calls.
o Declared using the auto keyword (though it’s rarely used because it's the
default).
4. Example:
void demo() {
int x = 10; // Automatic variable
x++;
printf("%d", x); // Output: 11
}
55
Easy2Siksha
External Variables:
1. Definition: These are global variables, meaning they are declared outside all
functions and can be accessed and modified by any function in the program.
2. How It Works: Think of it like a shared family bank account that everyone in the
family can access and change.
3. Characteristics:
o Declared using the extern keyword.
o Exist for the entire lifetime of the program.
o Useful for sharing information between multiple functions.
4. Example:
int x = 10; // External variable
void demo() {
x++;
printf("%d", x); // Output: 11
}
int main() {
demo();
return 0;
}
Static Variables:
1. Definition: These variables retain their value between multiple function calls. They
are declared inside a function but are not destroyed when the function ends.
2. How It Works: Think of it like storing leftover food in a fridge. Even after the meal is
over (function ends), the food (variable) remains until you use it again.
3. Characteristics:
o Declared using the static keyword.
o Their value persists between function calls.
o Useful for tracking things like counters.
56
Easy2Siksha
4. Example:
void demo() {
static int x = 10; // Static variable
x++;
printf("%d", x);
}
int main() {
demo(); // Output: 11
demo(); // Output: 12
return 0;
}
The value of x is retained between function calls.
User-Defined Functions vs. Library Functions
User-Defined Functions:
1. Definition: Functions that are written by the programmer to perform specific tasks in
a program.
2. How It Works: Imagine building a custom tool in your workshop for a unique task.
You decide how it works, what it does, and when to use it.
3. Characteristics:
o Written to handle tasks specific to the program’s needs.
o Offer better control and flexibility.
o Require the programmer to define their behavior and logic.
4. Example:
int add(int a, int b) {
return a + b; // Adds two numbers
}
int main() {
int result = add(5, 10); // Output: 15
57
Easy2Siksha
return 0;
}
Library Functions:
1. Definition: Predefined functions provided by programming languages to perform
common tasks like input/output operations, mathematical calculations, and string
manipulations.
2. How It Works: Think of it like ready-made kitchen appliancesno need to make your
own tools; just use what’s available.
3. Characteristics:
o Provided by the language or compiler.
o Reduce development time since they are already optimized and tested.
o Require importing libraries (e.g., #include <stdio.h> in C).
4. Example:
#include <math.h>
int main() {
double result = sqrt(25); // Library function to find square root
return 0;
}
Here, the sqrt function is a library function that calculates the square root of a number.
Key Takeaways:
1. Call-by-Value vs. Call-by-Reference:
o Call-by-Value creates a copy and does not modify the original value.
o Call-by-Reference directly modifies the original value.
2. Variable Types:
o Automatic variables exist temporarily.
o External variables are global and shared across the program.
o Static variables retain their value across multiple function calls.
3. User-Defined vs. Library Functions:
o User-Defined functions are custom and specific to a task.
58
Easy2Siksha
o Library functions are pre-built and ready to use for common operations.
By understanding these concepts, you'll have a solid foundation for managing data and
organizing your code effectively in any programming language.
Note: This Answer Paper is totally Solved by Ai (Artificial Intelligence) So if You find Any Error Or Mistake . Give us a
Feedback related Error , We will Definitely Try To solve this Problem Or Error.